package org.springframework.boot;

import org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor;
import org.springframework.boot.context.event.EventPublishingRunListener;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.EnvironmentPostProcessorApplicationListener;
import org.springframework.boot.logging.DeferredLogs;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.SpringFactoriesLoader;

import java.util.List;

public class Step5 {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication();
        ApplicationEnvironment env = new ApplicationEnvironment();
        //EnvironmentPostProcessor是配置在spring.factories文件中
        List<String> names = SpringFactoriesLoader.loadFactoryNames(EnvironmentPostProcessor.class, Step5.class.getClassLoader());
//        for (String name : names) {
//            System.out.println(name);
//        }

        //以上的后处理器是通过监听器ApplicationListener来实现的，该监听器中有一个EnvironmentPostProcessorApplicationListener的监听器
        app.addListeners(new EnvironmentPostProcessorApplicationListener());

        //发布事件来触发EnvironmentPostProcessorApplicationListener监听器
        EventPublishingRunListener publisher = new EventPublishingRunListener(app, args);
        System.out.println("发布事件前-----------------");
        for (PropertySource<?> ps : env.getPropertySources()) {
            System.out.println(ps);
        }
        publisher.environmentPrepared(new DefaultBootstrapContext(),env);
        System.out.println("发布事件后-----------------");
        for (PropertySource<?> ps : env.getPropertySources()) {
            System.out.println(ps);
        }

        //获取application.properties文件中的属性值
        System.out.println(env.getProperty("server.port"));
    }

    public void test(){
        SpringApplication app = new SpringApplication();
        ApplicationEnvironment env = new ApplicationEnvironment();

        System.out.println("增强前-----------------");
        for (PropertySource<?> ps : env.getPropertySources()) {
            System.out.println(ps);
        }

        //增加后处理器，处理application.properties文件
        ConfigDataEnvironmentPostProcessor postProcessor = new ConfigDataEnvironmentPostProcessor(new DeferredLogs(), new DefaultBootstrapContext());
        postProcessor.postProcessEnvironment(env,app);

        System.out.println("增强后-----------------");
        for (PropertySource<?> ps : env.getPropertySources()) {
            System.out.println(ps);
        }

        //获取application.properties文件中的属性值
        System.out.println(env.getProperty("server.port"));
    }
}
